<script lang="ts" setup>
import { useForm } from '@/hooks/web/useForm'
import { FormSchema } from '@/types/form'
import * as CatalogApi from '@/api/course/catalog'
import { CatalogTree } from '@/api/course/catalog'
import { CourseVO } from '@/api/course'

const message = useMessage()
const { t } = useI18n()

const dialogVisible = ref(false)
const dialogTitle = ref('新增课程')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')

const courseId = ref<string | null>(null)
const catalogTree = ref<CatalogTree[]>([])

const schema = reactive<FormSchema[]>([
  {
    field: 'parentId',
    label: '上级目录',
    component: 'TreeSelect',
    componentProps: {
      data: catalogTree,
      'check-strictly': true,
      props: { label: 'catalogName', value: 'id' }
    },
    value: ''
  },
  {
    field: 'catalogName',
    label: '目录名称',
    component: 'Input',
    value: '',
    formItemProps: {
      rules: [{ required: true, message: '请输入目录名称' }]
    }
  },
  {
    field: 'catalogDesc',
    label: '目录描述',
    component: 'Input',
    componentProps: { type: 'textarea' },
    value: '',
    formItemProps: {
      rules: [
        // 长度不大于100个字符
        {
          max: 100,
          message: '目录描述不可超过100个字',
          trigger: ['blur', 'change']
        }
      ]
    }
  },
  {
    field: 'catalogStatus',
    label: '目录状态',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '启用',
          value: 1
        },
        {
          label: '禁用',
          value: 2
        }
      ]
    },
    value: 1,
    formItemProps: {
      rules: [{ required: true, message: '请输入目录名称' }]
    }
  },
  {
    field: 'sortNo',
    label: '排序',
    component: 'InputNumber',
    value: 1,
    formItemProps: {
      rules: [{ required: true, message: '请输入目录名称' }]
    }
  }
])

const { register, elFormRef, methods: formMethods } = useForm()

const open = (
  type: 'create' | 'update',
  _catalogTree: CatalogTree[],
  currentCatalogId: CatalogTree['id'],
  currentCourseId: CourseVO['id'],
  id?: string
) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'update' ? '编辑目录' : '新增目录'
  formType.value = type
  catalogTree.value = _catalogTree
  courseId.value = currentCourseId

  formMethods.setValues({
    parentId: currentCatalogId
  })

  if (type === 'update') {
    formLoading.value = true
    CatalogApi.get(id!).then((data) => {
      formMethods.setValues(data)
      formLoading.value = false
    })
  }
}
defineExpose({ open })

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!elFormRef.value) return
  const valid = await elFormRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true

  try {
    const formData = (await formMethods.getFormData()) || {}

    if (formType.value === 'create') {
      // 新增
      const data: CatalogApi.CatalogCreateDTO = { ...(formData as any), courseId: courseId.value }

      await CatalogApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      // 更新
      const data: CatalogApi.CatalogDTO = { ...(formData as any), courseId: courseId.value }

      await CatalogApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>

<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="700">
    <Form :schema="schema" @register="register" />
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
